# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

### Channel code generation, acquisition and configuration management
# 信道代码生成、获取和配置管理


from builtins import print
from calendar import c
from flask import Blueprint
from flask import request
import utils.pgsql.pgchannel as channel
from utils.wraps import token, urlcost
import utils.message.response as response
import json
import utils.common.log as log
import requests
import uuid
import utils.common.initres as initres
import utils.pgsql.pgpay as pgpay
import utils
import datetime
import utils.pgsql.pgvlogrecord as record
if initres.COS_TYPE :
    import utils.oss.cos as oss   
else :
    import utils.oss.oss as oss




channel_module = Blueprint("channel_channelment", __name__, url_prefix="/api/v1/channel/channelment")


@channel_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def point_add():
     

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1, 2, 3]:
        obj = channel.PgChannel()
        dic = json.loads(request.data)
        channelappinfor = ""
        data = {}
        data["check_path"] = True
        data["env_version"] = "release"

        if "pagePath" in dic:
            if obj.channelname(dic["channelName"], dic["caseId"]) != []:
                return response.make_response_1505()
            if obj.caseorcode(dic["pagePath"], dic["caseId"]) != []:
                pass # 暂时放过
                # return response.make_response_1530()
            if userInfo["role"] == 1 and not dic['operatorId']:#1 超级管理员
                dic['operatorId'] = 1
            if userInfo["role"] == 1 and not dic['pointId']:
                dic.pop('pointId')
            res = obj.addChannel(dic)
            data["scene"] = "caseId=" + str(dic["caseId"]) + ",channelId=0"
            if "people" in dic:
                data["scene"] = (
                        "caseId=" + str(dic["caseId"]) + ",channelId=" + str(res["channelId"]) +
                        ",p=" + str(dic["people"])
                )
        else:
            if obj.sellerId(dic["sellerId"]) != []:
                return response.make_response_1530()
            res = obj.addChannel(dic)
            data["scene"] = (
                "caseId=" + str(dic["caseId"]) + ",channelId=" + str(res["channelId"])
            )
            if "people" in dic:
                data["scene"] = (
                        "caseId=" + str(dic["caseId"]) + ",channelId=" + str(res["channelId"]) +
                        ",p=" + str(dic["people"])
                )
 
        data["page"] = "pages/customCamera/cameras" 
        channelappinfor = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf208c5902a55d25b&secret=ad3a871b6198e2a179409002b3b79c10"

        url = "http://127.0.0.1:33033/api/v1/channel/channelment/weixin"
        infor = {
            "channelappinfor": channelappinfor,
            "data": json.dumps(data),
            "channelId": res["channelId"],
        }
        body = json.dumps(infor)
        res = requests.post(url, body, headers={"content-type": "application/json"})
        return json.loads(res.text)


@channel_module.route("/unchannel", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def unchannel():
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = channel.PgChannel()

    if userInfo["role"] == 2:
        operatorId = userInfo["operatorId"]
        return response.make_response_success(obj.allunchanneloperator(operatorId))
    elif userInfo["role"] == 3:
        operatorId = userInfo["operatorId"]
        caseId = userInfo["caseId"]
        return response.make_response_success(obj.allunchannelcase(operatorId, caseId))
    else:
        return response.make_response_401()


@channel_module.route("/weixin", methods=["POST"])
@urlcost.cost_count_wraps
def weixin():
    obj = channel.PgChannel()
    data = request.get_data()
    dic = json.loads(data)
    try:
        response3 = requests.get(
            dic["channelappinfor"], headers={"content-type": "application/xml"}
        )
        access_token = json.loads(response3.text)["access_token"]
        response2 = requests.post(
            "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="
            + access_token,
            dic["data"],
            headers={"content-type": "application/json"},
        )
        log.logging.info(dic["data"])
        log.logging.info(response2.content)
        if "errcode" in str(response2.content):
            obj.delete(dic["channelId"])
            return response.make_response_1000()
        else:
            filename = initres.UPLOADPATH + str(uuid.uuid1()) + ".png"
            with open(filename, "wb") as f:
                f.write(response2.content)

            filename = oss.upload_webRes(filename)
            log.logging.info(filename)
            obj.modify(dic["channelId"], {"orCode": filename})
            return response.make_response_success({"channelId": dic["channelId"]})
    except:
        obj.delete(dic["channelId"])
        return response.make_response_1004()


@channel_module.route("/<int:channelId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def point_put(channelId):
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [2, 3]:
        obj = channel.PgChannel()
        dic = json.loads(request.data)
        if "channelName" in dic:
            if obj.channeleditname(dic["channelName"], dic["caseId"], channelId) != []:
                return response.make_response_1505()
        if obj.modify(channelId, dic):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@channel_module.route("/<int:channelId>", methods=["DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def point_delete(channelId):
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = channel.PgChannel()

        if obj.delete(channelId):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@channel_module.route("/admin/<int:adminId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def seller_all_admin(adminId):
   
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = channel.PgChannel()
    if userInfo["role"] == 1:
        return response.make_response_success(obj.all_cases())
    elif userInfo["role"] == 2:
        operatorId = userInfo["operatorId"]
        return response.make_response_success(obj.allByoperator(operatorId))
    elif userInfo["role"] == 3:
        caseId = userInfo["caseId"]
        return response.make_response_success(obj.allBycaseId(caseId))
    elif userInfo["role"] == 6:
        obj_admin = utils.pgsql.pgadmin.PgAdmin()
        case_list = obj_admin.get_city_cases(adminId)['caseName']
        return response.make_response_success(obj.all_ByCaseIds(case_list))
    else:
        return response.make_response_401()


 
@channel_module.route("/channelall", methods=["GET"])
@urlcost.cost_count_wraps
def channel_all():
  
    obj = channel.PgChannel()
    res = obj.all()
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()

 
@channel_module.route("/case/channelall/<int:caseId>", methods=["GET"])
@urlcost.cost_count_wraps
def channel_case_all(caseId):

    obj = channel.PgChannel()
    res =  obj.allBycaseId(caseId)
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()



@channel_module.route("/case/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def seller_all_caseId(caseId):
  

    obj = channel.PgChannel()
    return response.make_response_success(obj.allBycaseId(caseId))

def deviation_date(date, offsets):
    start_date = datetime.datetime.strptime(date, "%Y-%m-%d")
    now_date = datetime.timedelta(days=offsets)
    a = start_date + now_date
    return a.strftime("%Y-%m-%d")

@channel_module.route("/case/count", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def count_all_caseId():
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    Info = json.loads(request.data)
    if len(Info[1]) == 2:
        begin_date = Info[1][0]
        end_date = Info[1][1]
    else:
        grant_date = ''
        if userInfo["role"] == 6:# 城市账号的授权日期
            obj = record.PgRecord()
            grant_date = obj.get_grant_date(userInfo['adminId'])
        begin_date = grant_date
        end_date = "2099-12-30"
    obj = pgpay.PgPay()
    peoples = obj.get_case_people(Info[0])
    people_list = [i['people'] for i in peoples if i['people']]
    count=[0,0,{},{}]# 总数，金额，项目金额，人员金额
    if peoples:
        tmp = {p:0 for p in people_list}
        count[3] = tmp
    ret = obj.chanpaycount(
        Info[0],
        datetime.datetime.strptime(begin_date, "%Y-%m-%d"),
        datetime.datetime.strptime(deviation_date(end_date, +1), "%Y-%m-%d"),
        play=Info[2]
    )
    count[0]=len(ret)
    for i in ret:
        if i['order_status'] == 'success':
            count[1] = count[1] + i["totalFee"]
            if i['people']:
                count[3][i['people']] += i["totalFee"]
        play_name = i["templateName"].split('_')[1] #项目名
        if play_name not in count[2]:
            count[2][play_name] = 0
        if i['order_status'] == 'success':
            count[2][play_name] = count[2][play_name] + i["totalFee"]
    return response.make_response_success(count)